class MemoController < ApplicationController

  # GET: 未登陆时的介绍
  def note
  end

  # GET: 列表显示
  def index

  	# 未登录
  	if(session[:user] == nil)
  		render 'note.html.erb'
  		return
  	end

  	# 已登录
  	@user = session[:user]
  	@memos = @user.memos.where(:isdeleted => 0).paginate(:page => params[:page], :per_page => 10).order("updated_at desc")

  end

  # POST: 保存新的便笺
  def create
  	@memo = Memo.new
  	@memo.userid = session[:user].id
  	@memo.content = params[:content]
  	render :text => if (unlogin and @memo.save) then @memo.id.to_s else "0" end
  end

  # POST: 删除便笺
  def delete
  	_isok = false
  	if(unlogin)
  		@user = session[:user]
	  	@memo = @user.memos.find(params[:memoid])
	  	if(@memo != nil)
	  		@memo.isdeleted = 1
	  		_isok = @memo.save
	  	end
	end
  	render :text => if(_isok) then '1' else '0' end
  end

  # POST: 修改便笺
  def update
    _success = false
    if(unlogin)
      @user = session[:user]
      @memo = @user.memos.find(params[:memoid])
      if(@memo != nil)
        @memo.content = params[:content]
        _success = @memo.save
      end
    end
    render :text => if(_success) then @memo.id.to_s else '0' end
  end


  #—————————————————————————————————— 后台管理 ————————————————————————# 

  # GET: 管理.便笺列表
  def admin_memolist
    return unless checkAdmin
    _where = '1=1'
    _where << " and userid=#{params[:userid]}" if(params[:userid] != nil)
    @memolist = Memo.select('id, userid, content, created_at, updated_at, isdeleted').where(_where).includes(:user).paginate(:page => params[:page], :per_page => 10).order("created_at desc")
    render :template => 'admin/memolist.html.erb'
  end

  # POST: 管理.物理单条便笺（仅删除已标记为逻辑删除的）
  def admin_memodelete
    return unless checkAdmin
    __success = false
    memo = Memo.find(params[:id])
    if(memo != nil)
      if(memo[:isdeleted] == 1)
        __success = memo.destroy
      end
    end
    render :text => __success
  end

private

  def unlogin
    # 未登录状态
    if(session[:user] == nil)
      redirect_to :action => 'login', :controller =>'user'
      return false
    end
    true
  end

end
